<template>
  <div class="addBrand-container">
    <div class="container">
      <el-form ref="ruleForm"
               :model="ruleForm"
               :rules="rules"
               :inline="true"
               label-width="180px"
               class="demo-ruleForm">
        <div>
          <el-form-item label="专业名称:" prop="name">
            <el-input v-model="ruleForm.name"
                      placeholder="请填写专业名称"
                      maxlength="14" />
          </el-form-item>
        </div>
        
        <div>
          <el-form-item label="专业图片:" required prop="image">
            <image-upload :prop-image-url="imageUrl"
                          @imageChange="imageChange">
              图片大小不超过2M<br>仅能上传 PNG JPEG JPG类型图片<br>建议上传200*200或300*300尺寸的图片
            </image-upload>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="专业所属学院:" required prop="collegeId">
            <!-- 修改后的下拉选择框 -->
            <el-select v-model="ruleForm.collegeId" 
                       placeholder="请选择所属学院"
                       clearable
                       filterable
                       @change="handleCollegeChange">
              <el-option 
                v-for="college in collegeList"
                :key="college.id"
                :label="college.name"
                :value="college.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="address">
          <el-form-item label="专业描述:">
            <el-input v-model="ruleForm.description"
                      type="textarea"
                      :rows="3"
                      maxlength="200"
                      placeholder="专业描述，最长200字" />
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-form-item>
            <el-button @click="() => $router.back()">
              取消
            </el-button>
            <el-button type="primary"
                       :class="{ continue: actionType === 'add' }"
                       @click="submitForm('ruleForm', false)">
              保存
            </el-button>
            <el-button v-if="actionType === 'add'"
                       type="primary"
                       @click="submitForm('ruleForm', true)">
              保存并继续添加
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import HeadLable from '@/components/HeadLable/index.vue'
import ImageUpload from '@/components/ImgUpload/index.vue'
import { addMajor, findMajorById, updateMajor } from '@/api/major'
import { getCollege } from '@/api/college' // 导入学院API
import { baseUrl } from '@/config.json'
import { FormInstance } from 'element-ui/types/form'

interface College {
  id: number;
  name: string;
}

interface MajorForm {
  name: string
  image: string
  collegeId: number | null
  description: string
  id?: string
}

@Component({
  name: 'AddMajor',
  components: {
    HeadLable,
    ImageUpload
  }
})
export default class extends Vue {
  private value: string = ''
  private seachKey: string = ''
  private dishList: any[] = []
  private imageUrl: string = ''
  private actionType: string = 'add'
  private dishTable: any[] = []
  private dialogVisible: boolean = false
  private checkList: any[] = []
  private collegeList: College[] = [] // 学院列表
  
  private ruleForm: MajorForm = {
    name: '',
    collegeId: null,
    image: '',
    description: ''
  }

  get rules() {
    return {
      name: {
        required: true,
        validator: (rule: any, value: string, callback: Function) => {
          if (!value) {
            callback(new Error('请输入专业名称'))
          } else if (!/^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/.test(value)) {
            callback(new Error('专业名称需2-20个字符（汉字、字母、数字）'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      },
      image: {
        required: true,
        message: '专业图片不能为空',
        trigger: 'blur'
      },
      collegeId: {
        required: true,
        message: '请选择学院',
        trigger: 'change'
      },
    }
  }

  async created() {
    // 获取学院列表
    await this.fetchCollegeList()
    
    this.actionType = this.$route.query.id ? 'update' : 'add'
    if (this.actionType === 'update') {
      const id = this.$route.query.id as string
      if (id) {
        findMajorById(Number(id))
          .then(res => {
            if (res.data.code === 1) {
              this.ruleForm = res.data.data
              this.imageUrl = this.ruleForm.image
              
              // 确保学院ID在列表中
              if (this.ruleForm.collegeId && !this.collegeList.some(c => c.id === this.ruleForm.collegeId)) {
                console.warn(`学院ID ${this.ruleForm.collegeId} 不在学院列表中`)
              }
            } else {
              this.$message.error(res.data.message)
              this.$router.push('/major')
            }
          })
          .catch(error => {
            console.error('获取专业信息失败:', error)
            this.$message.error('获取专业信息失败，请重试')
            this.$router.push('/major')
          })
      } else {
        this.$message.error('缺少专业ID')
        this.$router.push('/major')
      }
    }
  }

  // 获取学院列表
  private async fetchCollegeList() {
    try {
      const params = { page: 1, pageSize: 1000 } // 获取所有学院
      const response = await getCollege(params)
      
      if (response.data.code === 1) {
        this.collegeList = response.data.data.records || []
        
        // 如果没有数据，显示警告
        if (this.collegeList.length === 0) {
          this.$message.warning('学院列表为空，请先添加学院')
        }
      } else {
        this.$message.error(response.data.message || '获取学院列表失败')
      }
    } catch (error) {
      console.error('获取学院列表失败:', error)
      this.$message.error('获取学院列表失败，请重试')
    }
  }

  // 学院选择变化处理
  private handleCollegeChange(collegeId: number) {
    console.log('选择的学院ID:', collegeId)
    this.$forceUpdate() // 确保UI更新
  }

  // 其他方法保持不变...
  private seachHandle() {
    this.seachKey = this.value
  }

  $refs: {
    ruleForm: FormInstance;
  }
  
  public submitForm(formName: string, isContinue: boolean): void {
    this.$refs[formName].validate((valid: boolean) => {
      if (valid) {
        // 表单校验通过，发送axios请求
        if (this.actionType === 'add') {
          addMajor(this.ruleForm)
            .then(res => {
              if (res.data.code === 1) {
                this.$message.success('专业添加成功!')
                if (isContinue) {
                  this.ruleForm = {
                    name: '',
                    image: '',
                    collegeId: null,
                    description: ''
                  }
                  this.imageUrl = ''
                } else {
                  this.$router.push('/major')
                }
              } else {
                this.$message.error(res.data.message)
              }
            })
            .catch(error => {
              console.error('添加专业失败:', error)
              this.$message.error('添加学专业失败，请重试')
            })
        } else {
          // 修改操作
          updateMajor(this.ruleForm)
            .then(res => {
              if (res.data.code === 1) {
                this.$message.success('专业修改成功!')
                this.$router.push('/major')
              } else {
                this.$message.error(res.data.message)
              }
            })
            .catch(error => {
              console.error('更新专业失败:', error)
              this.$message.error('更新专业失败，请重试')
            })
        }
      }
    })
  }

  public imageChange(value: string): void {
    this.ruleForm.image = value
    this.imageUrl = value
  }

  private handleClose(): void {
    this.dialogVisible = false
  }

  private addTableList(): void {
    this.dialogVisible = false
  }

  private getCheckList(list: any[]): void {
    this.checkList = list
  }
}
</script>

<!-- 样式部分保持不变 -->
<style>
.avatar-uploader .el-icon-plus:after {
  position: absolute;
  display: inline-block;
  content: ' ' !important;
  left: calc(50% - 20px);
  top: calc(50% - 40px);
  width: 40px;
  height: 40px;
  background: url('./../../assets/icons/icon_upload@2x.png') center center no-repeat;
  background-size: 20px;
}
</style>

<style lang="scss">
.addBrand-container {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #ffc200;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 160px;
    line-height: 160px;
    text-align: center;
  }

  .avatar {
    width: 200px;
    height: 160px;
    display: block;
  }

  .el-input {
    width: 293px;
  }

  .address {
    .el-form-item__content {
      width: 777px !important;
    }
  }

  .el-input__prefix {
    top: 2px;
  }

  .addDish {
    .el-input {
      width: 130px;
    }

    .el-input-number__increase {
      border-left: solid 1px #fbe396;
      background: #fffbf0;
    }

    .el-input-number__decrease {
      border-right: solid 1px #fbe396;
      background: #fffbf0;
    }

    input {
      border: 1px solid #fbe396;
    }

    .table {
      border: solid 1px #ebeef5;
      border-radius: 3px;

      th {
        padding: 5px 0;
      }

      td {
        padding: 7px 0;
      }
    }
  }

  .addDishList {
    .seachDish {
      position: absolute;
      top: 12px;
      right: 20px;
    }

    .el-dialog__footer {
      padding-top: 27px;
    }

    .el-dialog__body {
      padding: 0;
      border-bottom: solid 1px #efefef;
    }

    .seachDish {
      .el-input__inner {
        height: 40px;
        line-height: 40px;
      }
    }
  }
  }
</style>

<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 30px;

    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      min-height: 500px;

      .subBox {
        padding-top: 30px;
        text-align: center;
        border-top: solid 1px $gray-5;
      }

      .addDish {
        width: 777px;

        .addBut {
          background: #ffc200;
          display: inline-block;
          padding: 0px 20px;
          border-radius: 3px;
          line-height: 40px;
          cursor: pointer;
          border-radius: 4px;
          color: #333333;
          font-weight: 500;
        }

        .content {
          background: #fafafb;
          padding: 20px;
          border: solid 1px #d8dde3;
          border-radius: 3px;
        }
      }
    }
  }
}
</style>